<script setup>
import { unref, inject, computed } from 'vue';

// 注入 App 组件中的内容
const todos = inject('todos');
const selectedAllTodo = inject('selectedAllTodo');
const delFinishedTodos = inject('delFinishedTodos');

// 定义计算属性  const finishedNum: ComputedRef<any>  定义的类型为 
const finishedNum = computed(() => {
  return todos.reduce((tatal, todo) => {
    // console.log("tatal", tatal);
    // console.log("todo", todo);
    return tatal + (todo.finished ? 1 : 0);
  }, 0);
});

const isChecked = computed({
  get: () => {
    // 由于计算属性被定义为 ComputedRef<any>，所以需要通过 .value 来获取值 或者 通过 unref 转为 非响应式的值
    // return finishedNum.value === todos.length && todos.length > 0
    return unref(finishedNum) === todos.length && todos.length > 0;
  },
  set: (value) => {
    console.log("计算属性获取 checkbox 值：", value);
    selectedAllTodo(value);
  }
});

// 定义方法
const finishedTodo = () => {
  delFinishedTodos();
};
</script>


<template>
  <div class="todo-footer">
    <label>
      <input type="checkbox" @change="change" v-model="isChecked">
    </label>
    <span>
      <span>已完成 {{ finishedNum }} 件</span>/ 总计 {{ todos.length }} 件
    </span>
    <button class="btn btn-warning" @click="finishedTodo">清楚已完成任务</button>
  </div>
</template>

<style scoped>
/* footer */
.todo-footer {
  height: 40px;
  line-height: 40px;
  padding-left: 6px;
  margin-top: 5px;
}

.todo-footer label {
  display: inline-block;
  margin-right: 20px;
  cursor: pointer;
}

.todo-footer label input {
  position: relative;
  top: -1px;
  vertical-align: middle;
}

.todo-footer button {
  float: right;
  margin-top: 5px;
}
</style>
